/*测试数据*/
var usertestdata=[
	{
		id: 1,
		userId: 2322,
		phone: 18817802281,
		realName: 'lisd',
		address: '上海市浦东新区',
		shoppingAddress: '上海市浦东新区',
		createTime: 1502937009,
		userMoney: 2366,
		taxType: '个人', //公司、个人
		taxCompany: '上海煜众网络科技有限公司',
		taxId: 'CX343344343',
		taxPhone: '18817802221',
		taxAddress: '上海工商银行宝山支行',
		taxBankId: '33222331453233434',
		taxBankName: '上海工商银行宝山支行'
	},
	{
		id: 2,
		userId: 2322,
		phone: 18817802281,
		realName: 'lisd',
		address: '上海市浦东新区',
		shoppingAddress: '上海市浦东新区',
		createTime: 1502937009,
		userMoney: 2366,
		taxType: '个人', //公司、个人
		taxCompany: '上海煜众网络科技有限公司',
		taxId: 'CX343344343',
		taxPhone: '18817802221',
		taxAddress: '上海工商银行宝山支行',
		taxBankId: '33222331453233434',
		taxBankName: '上海工商银行宝山支行'
	}
];
var protestdata=[
	{
		id: 1,
		productID: 2322,
		productName: "18817802281",
		productBrand: 'linda',
		productVersion: 'V3高规',
		store: 3455,
		singlePrice: 234,
		tradeCnt: 2234,
		createTime: 1502937009
	},
	{
		id: 2,
		productID: 334,
		productName: "18817802281",
		productBrand: 'linda',
		productVersion: 'V3高规',
		store: 3455,
		singlePrice: 234,
		tradeCnt: 2234,
		createTime: 1502937009
	}
];

$(function(){
    var role = localStorage.getItem("userRole");
    if(!(role!=null && role==7001)){
        consoleMes($("#manageContent"),2000,"success","无权限修改订单信息！");//success、info、warning、danger
        setTimeout(function () {
            window.location.href=gobalWeb+"orders/orders.html";
        }, 2500);
    }else{
        var tgid=getUrlParam("tgid");
        if(tgid!=null && tgid!=""){
            getOrderMes(tgid);
        }else{
            consoleMes($("#manageContent"),2000,"success","无法获取订单信息，请刷新测试！");//success、info、warning、danger
            setTimeout(function () {
                window.location.href=gobalWeb+"orders/orders.html";
            }, 2500);
        }

        orderNumChange();

        $("#productSearch").on('click',function(){
            searchProductData();
        });
        $("#productKeys").bind("keydown", function (e) {
            var key = e.which;
            if (key == 13){
                searchProductData();
            }
        });

        $("#clearProductSearch").on('click',function(){
            $("#proList").empty();
        });

        $("#btnCreateOrder").on('click',function(){
            createOrder();
        });
	}

});
/*获取订单信息*/
function getOrderMes(tgid) {
    $.post(
        gobalServer+"order/selectOne",
        {"orderId":tgid},
        function(backData){
            if(backData.statusCode==200){
                var order=backData.object;
                if(order!=null){
                    $("#manageContent").attr({"tgid":order.orderId});
                    getBuyProductDataMes(order.orderId);
                    getUserMes(order.userId);
                    $("#orderAddress").val(order.shoppingAddress);
                    $("#realName").val(order.realName);
                    $("#userPhone").val(order.userPhone);
                    $("#orderRemark").val(order.orderRemark);
				}else{
                    consoleMes($("#manageContent"),2000,"success","无法获取订单信息，请刷新测试！");//success、info、warning、danger
                    setTimeout(function () {
                        window.location.href=gobalWeb+"orders/orders.html";
                    }, 2500);
				}
            }else{
                consoleMes($("#manageContent"),3000,"warning",backData.msg);//success、info、warning、danger
            }
        }
    );
}
/*删除选购产品*/
function deleteBuyProduct(obj) {
    if(obj!=null){
        $(obj).parents(".buy-item").remove();
        console.log($(".buy-item").length);
        if($(".buy-item").length<=0){
            var $tr =$("<tr>").attr({"id":"noProductList"});
            var $td = $("<td>").attr({"colspan":9}).addClass("text-center").text("暂无选购产品！");
            $tr.append($td);
            $("#buyProList").append($tr);
        }else{
            $("#noProductList").remove();
        }
    }
}
/*产品价格修改*/
function editSinglePrice(obj) {
    var singlePrice=  $(obj).val();
    var substr=$(obj).parent(".buy-singlePrice").nextAll(".product-mes-list").children(".buy-product-mes").val();
    substr=substr.substring(0,substr.lastIndexOf("@"));
    var tNum=$(obj).parent(".buy-singlePrice").nextAll(".productNum").text().trim();
    $(obj).parent(".buy-singlePrice").nextAll(".totalPrice").text((tNum*1)*(singlePrice*1));
    $(obj).parent(".buy-singlePrice").nextAll(".product-mes-list").children(".buy-product-mes").val(substr+"@"+singlePrice);
}
/*购买产品信息展示*/
function buyProductMesShow(datarow){
    if(datarow!=null){
        if(datarow.length==undefined){
            var arr=[];
            arr.push(datarow);
            datarow=arr;
        }
        if(datarow.length>0){
            $("#buyProList").empty();
            var userRole= localStorage.getItem("userRole");
            $.each(datarow, function(i,item) {

                var $successtr =$("<tr>").addClass("success buy-item");
                var $productID =$("<td>").addClass("buy-productID").text(item.productId).attr({"tgid":item.productId});
                var $productName =$("<td>").addClass("buy-productName").text(item.productName);
                var $productBrand =$("<td>").addClass("buy-productBrand").text(item.productBrand);
                var $productVersion =$("<td>").addClass("buy-productVersion").text(item.productVersion);
                /*var $store =$("<td>").addClass("buy-store").text(item.store);*/
                var $editSinglePrice =$("<input>").addClass("edit-singlePrice").attr({"id":"price"+item.productId,"type":"number","min":"0.00","onchange":"editSinglePrice(this)"}).val(item.singlePrice);
                var $singlePrice=$("<td>").addClass("buy-singlePrice");
                $singlePrice.append($editSinglePrice);
                var $productNum =$("<td>").addClass("productNum").attr({"id":"num"+item.productId}).text(item.number);
                var $totalPrice =$("<td>").addClass("totalPrice").attr({"id":"totalprice"+item.productId}).text((item.number*1)*(item.singlePrice*1));
                var $buyBtntd =$("<td>").addClass("product-mes-list");
                var $buyBtn = $("<input>").addClass("btn btn-primary delete-product").attr({"type":"button","onclick":"deleteBuyProduct(this);"}).val("删除");
                $buyBtntd.append($buyBtn);
                var $buyPIdAndNum = $("<input>").addClass("buy-product-mes").attr({"id":"buy"+item.productId,"type":"text","hidden":"hidden"}).val(item.productId+"@"+item.number+"@"+item.singlePrice);
                $buyBtntd.append($buyPIdAndNum);
                $successtr.append($productID,$productName,$productBrand,$productVersion,$singlePrice,$productNum,$totalPrice,$buyBtntd);
                $("#buyProList").append($successtr);
            });
        }else{
            consoleMes($("#manageContent"),3000,"warning","无相关数据！");//success、info、warning、danger
        }

    }else{
        consoleMes($("#manageContent"),3000,"warning","无相关数据，请重试！");//success、info、warning、danger
    }
};
/*购买产品*/
function getBuyProductDataMes(tgid){
    if(tgid!=null && tgid!=""){
        /*var datarow = protestdata;
         productMesShow(datarow);*/
        $.post(
            gobalServer+"order/selectOrderDetailByOrderId",
            {"orderId":tgid},
            function(backData){
                if(backData.statusCode==200){
                    var datarow=backData.commonList;
                    buyProductMesShow(datarow);
                }else{
                    consoleMes($("#manageContent"),3000,"warning",backData.msg);//success、info、warning、danger
                }
            }
        );

    }
};
/*新增选购产品展示*/
function addNewProduct(obj) {
    if(obj!=null){
        var productIDs= $(".buy-productID").text();
        var productId=$(obj).parents(".product-item").children(".productID").text();
        var productName=$(obj).parents(".product-item").children(".productName").text();
        var productBrand=$(obj).parents(".product-item").children(".productBrand").text();
        var productVersion=$(obj).parents(".product-item").children(".productVersion").text();
        var store=$(obj).parents(".product-item").children(".store").text();
        var singlePrice=$(obj).parents(".product-item").children(".singlePrice").text();
        var productNum=$(obj).parents(".product-item").children(".productNum").children(".num-product").val();
        if((productNum*1)>(store*1)){
            consoleMes($("#manageContent"),3000,"warning","购买数量大于库存，无法加入！");
        }else{
            $("#noProductList").remove();
            if(productIDs.indexOf(productId)>=0){
                var num=$("#num"+productId).text();
                var tNum=(productNum*1)+(num*1);
                if((productNum*1)>(store*1)){
                    tNum=(store*1)+(num*1);
                    consoleMes($("#manageContent"),3000,"warning","购买数量不能大于库存！");
                }
                $("#num"+productId).text(tNum);
                $("#price"+productId).val(singlePrice);
                $("#totalprice"+productId).text((tNum*1)*(singlePrice*1));
                $("#buy"+productId).val(productId+"@"+tNum+"@"+singlePrice);
            }else{
                var userRole= localStorage.getItem("userRole");
                var $successtr =$("<tr>").addClass("success buy-item");
                var $productID =$("<td>").addClass("buy-productID").text(productId).attr({"tgid":productId});
                var $productName =$("<td>").addClass("buy-productName").text(productName);
                var $productBrand =$("<td>").addClass("buy-productBrand").text(productBrand);
                var $productVersion =$("<td>").addClass("buy-productVersion").text(productVersion);
                /*var $store =$("<td>").addClass("buy-store").text(store);*/
                if(userRole=="7001"){
                    var $editSinglePrice =$("<input>").addClass("edit-singlePrice").attr({"id":"price"+productId,"type":"number","min":"0.00","onchange":"editSinglePrice(this)"}).val(singlePrice);
                    var $singlePrice=$("<td>").addClass("buy-singlePrice");
                    $singlePrice.append($editSinglePrice);
                }else{
                    var $singlePrice =$("<td>").addClass("buy-singlePrice").text(singlePrice);
                }
                var $productNum =$("<td>").addClass("productNum").attr({"id":"num"+productId}).text(productNum);
                var $totalPrice =$("<td>").addClass("totalPrice").attr({"id":"totalprice"+productId}).text((productNum*1)*(singlePrice*1));
                var $buyBtntd =$("<td>").addClass("product-mes-list");
                var $buyBtn = $("<input>").addClass("btn btn-primary delete-product").attr({"type":"button","onclick":"deleteBuyProduct(this);"}).val("删除");
                $buyBtntd.append($buyBtn);
                var $buyPIdAndNum = $("<input>").addClass("buy-product-mes").attr({"id":"buy"+productId,"type":"text","hidden":"hidden"}).val(productId+"@"+productNum+"@"+singlePrice);
                $buyBtntd.append($buyPIdAndNum);
                $successtr.append($productID,$productName,$productBrand,$productVersion,$singlePrice,$productNum,$totalPrice,$buyBtntd);
                $("#buyProList").append($successtr);
            }
        }
    }


}
/*产品信息展示*/
function productMesShow(datarow){
    if(datarow!=null){
        if(datarow.length==undefined){
            var arr=[];
            arr.push(datarow);
            datarow=arr;
        }
        if(datarow.length>0){
            $("#proList").empty();
            $.each(datarow, function(i,item) {
                var $successtr =$("<tr>").addClass("success product-item");
                /*var $productrd =$("<td>").addClass("productrd");*/
                var $productID =$("<td>").addClass("productID").text(item.productId);
                var $productName =$("<td>").addClass("productName").text(item.productName);
                var $productBrand =$("<td>").addClass("productBrand").text(item.productBrand);
                var $productVersion =$("<td>").addClass("productVersion").text(item.productVersion);
                var $store =$("<td>").addClass("store").text(item.store);
                var $singlePrice =$("<td>").addClass("singlePrice").text(item.singlePrice);
                var $tradeCnt =$("<td>").addClass("tradeCnt").text(item.tradeCnt);

                /*var $radioIndex =$("<input>").addClass("radio-product").attr({'type':'radio','name':'proitem','singlePrice':item.singlePrice,'onclick':'productRadioSeleted(this)'}).val(item.productId);*/
                /*$productrd.append($radioIndex);*/

                var $buyNumtd =$("<td>").addClass("productNum");
                var $buyNum = $("<input>").addClass("num-product").attr({"type":"number","min":0,"max":item.store}).val(1);
                $buyNumtd.append($buyNum);
                var $buyBtntd =$("<td>").addClass("");
                var $buyBtn = $("<input>").addClass("btn btn-primary num-product").attr({"type":"button","onclick":"addNewProduct(this);"}).val("加入");
                $buyBtntd.append($buyBtn);

                $successtr.append($productID,$productName,$productBrand,$productVersion,$store,$singlePrice,$tradeCnt,$buyNumtd,$buyBtntd);
                $("#proList").append($successtr);
            });
        }else{
            consoleMes($("#manageContent"),3000,"warning","无相关数据！");//success、info、warning、danger
        }

    }else{
        consoleMes($("#manageContent"),3000,"warning","无相关数据，请重试！");//success、info、warning、danger
    }
};
/*搜索产品时*/
function searchProductData(){
    var productKeys= $("#productKeys").val().trim();
    if(productKeys!=null && productKeys!=""){
        /*var datarow = protestdata;
         productMesShow(datarow);*/
        $.post(
            gobalServer+"product/query",
            {"keyword":productKeys,"containZero":2},
            function(backData){
                if(backData.statusCode==200){
                    var datarow=backData.commonList;
                    productMesShow(datarow);
                }else{
                    consoleMes($("#manageContent"),3000,"warning",backData.msg);//success、info、warning、danger
                }
            }
        );
    }else{
        consoleMes($("#manageContent"),3000,"warning","请输入要搜索的关键字");
    }
};
/*客户信息展示*/
function userMesShow(datarow){
    if(datarow!=null){
        if(datarow.length==undefined){
            var arr=[];
            arr.push(datarow);
            datarow=arr;
        }
        if(datarow.length>0){
            $("#userList").empty();
            $.each(datarow, function(i,item) {
                var $successtr =$("<tr>").addClass("success user-item");
                var $userrd =$("<td>").addClass("userrd");
                var $userId =$("<td>").addClass("userId").text(item.userId);
                var $realName =$("<td>").addClass("realName").text(item.realName);
                var $phone =$("<td>").addClass("phone").text(item.phone);
                var $userMoney =$("<td>").addClass("userMoney").text(item.userMoney);
                var $address =$("<td>").addClass("address").text(item.address);
                var $shoppingAddress =$("<td>").addClass("shoppingAddress").text(item.shoppingAddress);
                var $radioIndex =$("<input>").addClass("radio-user").attr({'type':'radio','name':'useritem',"shoppingAddress":item.shoppingAddress,"checked":"checked"}).val(item.userId);
                $userrd.append($radioIndex);
                $successtr.append($userrd,$userId,$realName,$phone,$userMoney,$address,$shoppingAddress);

				/*展示开票信息*/
                var $infotr =$("<tr>").addClass("info user-item");
                var $taxMes =$("<td>").addClass("taxMes").attr({'colspan':7});
                var $taxh5=$("<h5>").text("客户:"+item.realName+"的开票信息：");
                var $taxType=$("<label>").addClass("label-ml").text("开票类型："+item.taxType);
                var $taxCompany=$("<label>").addClass("label-ml").text("开票公司："+item.taxCompany);
                var $taxId=$("<label>").addClass("label-ml").text("税务账号："+item.taxId);
                var $taxPhone=$("<label>").addClass("label-ml").text("开票电话："+item.taxPhone);
                var $taxAddress=$("<label>").addClass("label-ml").text("开票地址："+item.taxAddress);
                var $taxBankId=$("<label>").addClass("label-ml").text("开户行账户："+item.taxBankId);
                var $taxBankName=$("<label>").addClass("label-ml").text("开户行名称："+item.taxBankName);
                $taxMes.append($taxh5,$taxType,$taxCompany,$taxId,$taxPhone,$taxAddress,$taxBankId,$taxBankName);
                $infotr.append($taxMes);

                $("#userList").append($successtr,$infotr);
            });
        }else{
            consoleMes($("#manageContent"),3000,"warning","无相关数据！");//success、info、warning、danger
        }

    }else{
        consoleMes($("#manageContent"),3000,"warning","无相关数据，请重试！");//success、info、warning、danger
    }

};

/*获取客户信息*/
function getUserMes(tgid){

    if(tgid!=null && tgid!=""){
        $.post(
            gobalServer+"user/selectOne",
            {"userId":tgid},
            function(backData){
                if(backData.statusCode==200){
                    if(backData.object!=null){

                        var datarow = backData.object;
                        userMesShow(datarow);
                    }else{

                    }

                }else{
                    consoleMes($("#manageContent"),3000,"warning",backData.msg);//success、info、warning、danger
                }
            }
        );
    }

};

/*订单数量改变时间事件*/
function orderNumChange(){
	$("#ordernum").unbind().change(function(obj){
		var proid=$("input[name='proitem']:checked").val();
		if(proid!=null && proid!=""){
			var singlePrice=$("input[name='proitem']:checked").attr('singlePrice');
			var ordernum=$("#ordernum").val().trim();
			$("#orderTotal").text(singlePrice*ordernum);
		}
	});
};
/*保存订单*/
function createOrder(){
    var tgid=$("#manageContent").attr("tgid");
    if(tgid!=null && tgid!=""){
        var proids="";
        $(".buy-product-mes").each(function (i,obj) {
            if(i!=0){
                proids+="#";
            }
            proids+=$(obj).val().trim();
        });
        var userid=$("input[name='useritem']:checked").val();
        var orderAddress=$("#orderAddress").val().trim();
        var realName=$("#realName").val().trim();
        var userPhone=$("#userPhone").val().trim();
        var orderRemark=$("#orderRemark").val().trim();
        if(userid==null || userid==""){
            consoleMes($("#manageContent"),2000,"warning","请选择开店客户！");
            return;
        }
        if(proids==null || proids.length<=0){
            consoleMes($("#manageContent"),2000,"warning","请选购开单产品！");
            return;
        }
        if(orderAddress==null || orderAddress==""){
            consoleMes($("#manageContent"),2000,"warning","请输入送货地址！");
            return;
        }
        if(realName==null || realName==""){
            consoleMes($("#manageContent"),2000,"warning","请输入真实姓名！");
            return;
        }
        if(userPhone==null || userPhone=="" || !ischeckmobile(userPhone)){
            consoleMes($("#manageContent"),2000,"warning","请输入正确的联系方式！");
            return;
        }
        $.post(
            gobalServer+"order/updateOrderDetail",
            {"orderId":tgid,"productIdsAndNumbers":proids,"userId":userid,"shoppingAddress":orderAddress,"realName":realName,"userPhone":userPhone,"orderRemark":orderRemark},
            function(backData){
                if(backData.statusCode==200){
                    consoleMes($("#manageContent"),2000,"success","修改订单成功！");//success、info、warning、danger
                    setTimeout(function () {
                       window.location.href=gobalWeb+"orders/orders.html";
                    }, 2500);
                }else{
                    consoleMes($("#manageContent"),3000,"warning",backData.msg);//success、info、warning、danger
                }
            }
        );
    }else{
        consoleMes($("#manageContent"),2000,"success","数据问题，请刷新重试！");//success、info、warning、danger
	}

		
};
